package edu.calpoly.android.privatecontacts;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;

import android.annotation.TargetApi;
import android.app.ExpandableListActivity;
import android.app.SearchManager;
import android.content.Context;
import android.os.Build;
import android.os.Bundle;
import android.text.Editable;
import android.text.TextWatcher;
import android.util.Log;
import android.view.Menu;
import android.view.MenuItem;
import android.view.View;
import android.widget.EditText;
import android.widget.ExpandableListView;
import android.widget.ImageButton;
import android.widget.SearchView;
import android.widget.SearchView.OnQueryTextListener;

public class MainActivity extends ExpandableListActivity {
	
    ExpandableListAdapter listAdapter;
    ExpandableListView expListView;
    List<String> listDataHeader;
    HashMap<String, List<String>> listDataChild;
    EditText searchBox;
    ImageButton searchButton;
    
	@Override
	protected void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.HONEYCOMB) {
			setContentView(R.layout.contacts_list);
		} else {
			setContentView(R.layout.old_version_contacts_list);
			searchBox = (EditText) this.findViewById(R.id.search_box);
			searchBox.addTextChangedListener(new TextWatcher() {

				@Override
				public void afterTextChanged(Editable arg0) {
					// TODO Auto-generated method stub
					
				}

				@Override
				public void beforeTextChanged(CharSequence s, int start, int count, int after) {
					// TODO Auto-generated method stub
					
				}

				@Override
				public void onTextChanged(CharSequence s, int start, int before, int count) {
					Log.d("ONKEY", "test is "+ s + ", demarcated by "+start+ ", "+before+", "+count);
					Log.d("ONKEY", "text is "+ searchBox.getText().toString());
					showMatchingEntries(searchBox.getText().toString());
					expandCategories();
				}

			});
			searchButton = (ImageButton) this.findViewById(R.id.search_button);
		}

        // get the listview
        expListView = this.getExpandableListView();
        expListView.setOnChildClickListener(new ExpandableListView.OnChildClickListener() {
			
			@Override
			public boolean onChildClick(ExpandableListView parent, View v, int groupPosition, int childPosition, long id) {
				Log.d("ONCHILDCLICK", "parent is "+groupPosition+ ", child is " +childPosition+ "id is "+id);
				Log.d("ONCHILDCLICK", "CHILD is "+listDataChild.get( listDataHeader.get(groupPosition) ).get(childPosition) );

				return false;
			}
		});
 
        // preparing list data
        prepareListData();
 
        listAdapter = new ExpandableListAdapter(this, listDataHeader, listDataChild);
 
        // setting list adapter
        expListView.setAdapter(listAdapter);
	}

	@TargetApi(Build.VERSION_CODES.HONEYCOMB)
	@Override
	public boolean onCreateOptionsMenu(Menu menu) {
		// Inflate the menu; this adds items to the action bar if it is present.
		getMenuInflater().inflate(R.menu.main, menu);
		if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.HONEYCOMB) {
			SearchManager searchManager = (SearchManager) getSystemService(Context.SEARCH_SERVICE);
			SearchView    searchView    = (SearchView)    menu.findItem(R.id.search).getActionView();
			searchView.setSearchableInfo(searchManager.getSearchableInfo(getComponentName()));
		
			searchView.setOnQueryTextListener(new OnQueryTextListener() {
	
				@Override
				public boolean onQueryTextChange(String querytext) {
					Log.d("QUERYLISTENER", "query text is "+querytext+ ("null?"+querytext==null));
	//				if (querytext.length() > 1) {
						showMatchingEntries(querytext);
						expandCategories();
	//				}
					return true;
				}
	
				@Override
				public boolean onQueryTextSubmit(String querytext) {
					Log.d("QUERYLISTENER", "query submitted is "+querytext);
					return true;
				}
				
			});
		}
		
		return true;
	}
	
	@Override
	public boolean onOptionsItemSelected(MenuItem item) {
	    switch (item.getItemId()) {
//	        case R.id.search:
//
//	        	Log.d("OPTIONSELECTED", "now calling onSearchRequested()");
//	        	onSearchRequested();
//	            return true;
	        default:
	            return false;
	    }
	}
	
	private void showMatchingEntries(String querytext) {
//		ExpandableListView lv = this.getExpandableListView();
//        listDataHeader = new ArrayList<String>();
        listDataChild.get("Students").clear();// = new HashMap<String, List<String>>();
        listDataChild.get("Teachers").clear();// = new HashMap<String, List<String>>();
        listDataChild.get("Staff").clear();// = new HashMap<String, List<String>>();
        
//        listDataHeader.add("Teachers");
        // I am having trouble with data types in this next block.
//        List<String> students = new ArrayList<String>();
        for (String student : this.getResources().getStringArray(R.array.teachers)) {
        	if (student.toLowerCase().contains(querytext.toLowerCase())) {
        		listDataChild.get("Students").add(student);
        	} else {
        		Log.d("TAG", "no match "+student+ " and "+ querytext);
        	}
        }
//        List<String> teachers = new ArrayList<String>();
        for (String teacher : this.getResources().getStringArray(R.array.teachers)) {
        	if (teacher.toLowerCase().contains(querytext.toLowerCase())) {
        		listDataChild.get("Teachers").add(teacher);
        	} else {
        		Log.d("TAG", "no match "+teacher+ " and "+ querytext);
        	}
        }
//        List<String> staff = new ArrayList<String>();
        for (String staff : this.getResources().getStringArray(R.array.teachers)) {
        	if (staff.toLowerCase().contains(querytext.toLowerCase())) {
        		listDataChild.get("Staff").add(staff);
        	} else {
        		Log.d("TAG", "no match "+staff+ " and "+ querytext);
        	}
        }
//        listDataChild.put(listDataHeader.get(0), teachers);
        this.listAdapter.notifyDataSetChanged();
	}
	
	private void expandCategories() {
		this.getExpandableListView().expandGroup(0);
		this.getExpandableListView().expandGroup(1);
		this.getExpandableListView().expandGroup(2);
	}
	
	private void prepareListData() {
        listDataHeader = new ArrayList<String>();
        listDataChild = new HashMap<String, List<String>>();
        
        listDataHeader.add("Students");
        List<String> students = new ArrayList<String>();
        for (String teacher : this.getResources().getStringArray(R.array.teachers)) {
        	students.add(teacher);
        }
        listDataChild.put(listDataHeader.get(0), students);
        
        listDataHeader.add("Teachers");
        List<String> teachers = new ArrayList<String>();
        for (String teacher : this.getResources().getStringArray(R.array.teachers)) {
        	teachers.add(teacher);
        }
        listDataChild.put(listDataHeader.get(1), teachers);
        
        listDataHeader.add("Staff");
        List<String> staff = new ArrayList<String>();
        for (String teacher : this.getResources().getStringArray(R.array.teachers)) {
        	staff.add(teacher);
        }
        listDataChild.put(listDataHeader.get(2), staff);
	}
	
	@SuppressWarnings("unused")
	private void showDetailOf(int parentPosition, int childPositionq) {
		
	}

}
